package com.coocaa.ops.admin.v1.upload.util;

import com.coocaa.ops.admin.v1.upload.exception.ApkParseException;
import com.coocaa.ops.admin.v1.upload.model.ApkInfoModel;
import com.coocaa.ops.admin.v1.upload.properties.UploadProperties;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author bijiahao
 * @date : 2019/2/18.
 * @description
 */
@Slf4j
public class ApkAnalyzerUtil {
    /**
     * AAPT 命令
     */
    private static final String AAPT_DUMP_CMD = "aapt dump badging ";
    /**
     * APK信息-包名
     */
    private static final String PACKAGE = "package";
    /**
     * APK信息-SDK版本
     */
    private static final String SDK_VERSION = "sdkVersion";
    /**
     * APK信息-目标SDK版本
     */
    private static final String TARGET_SDK_VERSION = "targetSdkVersion";
    /**
     * APK信息-启动活动
     */
    private static final String LAUNCHABLE_ACTIVITY = "launchable-activity";
    /**
     * APK信息-应用
     */
    private static final String APPLICATION = "application";
    /**
     * APK信息-应用标签
     */
    private static final String APPLICATION_LABEL = "application-label";
    /**
     * APK信息-标签
     */
    private static final String APPLICATION_LABEL_ZH = "application-label-zh";
    /**
     * APK信息-标签
     */
    private static final String APPLICATION_LABEL_ZH_CN = "application-label-zh_CN";
    /**
     * APK信息-屏幕密度
     */
    private static final String DENSITIES = "densities";
    /**
     * APK信息-本地代码
     */
    private static final String NATIVE_CODE = "native-code";
    /**
     * APK信息-支持屏幕
     */
    private static final String SUPPORTS_SCREENS = "supports-screens";
    /**
     * APK信息-本地环境
     */
    private static final String LOCALES = "locales";
    /**
     * APK信息-应用图标
     */
    private static final String APPLICATION_ICON = "application-icon";

    /**
     * 解析APK信息
     *
     * @param apkFilePath
     * @return
     */
    public static ApkInfoModel getApkInfo(String apkFilePath) {
        ApkInfoModel apkInfo = new ApkInfoModel();
        Process process = null;
        //获取apk解析命令
        String apkParseCmd = getApkParseCmd(apkFilePath);
        log.debug("====AAPT命令: " + apkParseCmd);
        BufferedReader bufferedReader = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            process = runtime.exec(apkParseCmd);
            if (null == process) {
                return apkInfo;
            }
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                log.debug("====" + line);
                getApkInfo(line, apkInfo);
            }
        } catch (IOException e) {
            String errMsg = "Parse the APK: " + ExceptionUtil.getStackTraceAsString(e);
            log.error(errMsg);
            throw new ApkParseException(errMsg);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return apkInfo;
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    /**
     * 获取APK解析 命令
     * 命令示例:
     * /Users/bijiahao/develop/aapt/aapt dump badging /Users/bijiahao/upload/apk/tvos6_imgs_dev/apk/20180207/20180207164438804458.apk
     * 注意:
     * <ul>
     * <li>/Users/bijiahao/develop/aapt/ 为AAPT工具所在目录</li>
     * <li>aapt dump badging 为解析命令</li>
     * <li>/Users/bijiahao/upload/apk/tvos6_imgs_dev/apk/20180207/20180207164438804458.apk 文件路径</li>
     * </ul>
     *
     * @param apkFilePath
     * @return
     */
    private static String getApkParseCmd(String apkFilePath) {
        StringBuffer cmd = new StringBuffer();
        String aaptDir = UploadProperties.Constants.APK_AAPT_DIR;
        cmd.append(aaptDir);
        if (!aaptDir.endsWith("/")) {
            cmd.append("/");
        }
        cmd.append(AAPT_DUMP_CMD)
                .append(apkFilePath);
        return cmd.toString();
    }

    /**
     * 解析APK信息
     *
     * @param line
     * @param apkInfo
     */
    private static void getApkInfo(String line, ApkInfoModel apkInfo) {
        String eachLineInfo = line.replace("'", "");
        String[] nameValPair = eachLineInfo.split(":");
        if (PACKAGE.equals(nameValPair[0])) {
            //设置包名等
            handleSetPackageAndVersionInfo(nameValPair[1], apkInfo);
        } else if (SDK_VERSION.equals(nameValPair[0])) {
            //获取SDK版本信息
            apkInfo.setSdkversion(Integer.parseInt(nameValPair[1]));
        } else if (TARGET_SDK_VERSION.equals(nameValPair[0])) {
            //获取目标SDK版本信息
            apkInfo.setTargetSdkversion(Integer.parseInt(nameValPair[1]));
        } else if (LAUNCHABLE_ACTIVITY.equals(nameValPair[0])) {
            //设置启动活动
            handleSetLaunchableActivity(nameValPair[1], apkInfo);
        } else if (APPLICATION.equals(nameValPair[0])) {
            //获取 应用
            handleSetAppLabelAndIconsInfo(nameValPair[1], apkInfo);
        } else if (APPLICATION_LABEL.equals(nameValPair[0])) {
            //获取 应用标签
            apkInfo.setApplicationLabel(nameValPair[1]);
        } else if (APPLICATION_LABEL_ZH.equals(nameValPair[0])) {
            //获取 应用标签
            apkInfo.setApplicationLabel(nameValPair[1]);
        } else if (APPLICATION_LABEL_ZH_CN.equals(nameValPair[0])) {
            //获取 应用标签
            apkInfo.setApplicationLabel(nameValPair[1]);
        } else if (DENSITIES.equals(nameValPair[0])) {
            //获取 屏幕密度
            apkInfo.setDensities(nameValPair[1]);
        } else if (NATIVE_CODE.equals(nameValPair[0])) {
            //获取 本地代码
            apkInfo.setNativeCode(nameValPair[1]);
        } else if (SUPPORTS_SCREENS.equals(nameValPair[0])) {
            //获取 支持屏幕
            apkInfo.setSupportsScreens(nameValPair[1]);
        } else if (LOCALES.equals(nameValPair[0])) {
            //获取 本地环境
            apkInfo.setLocales(nameValPair[1]);
        } else if (nameValPair[0].contains(APPLICATION_ICON)) {
            //获取 应用图标
            apkInfo.setApplicationLabel(nameValPair[1]);
        }
    }

    /**
     * 设置包名和版本号等
     *
     * @param val
     * @param apkInfo
     */
    private static void handleSetPackageAndVersionInfo(String val, ApkInfoModel apkInfo) {
        //获取包名信息
        String[] packInfo = val.trim().split(" ");
        int length = packInfo.length;
        for (int i = 0; i < length; i++) {
            if (packInfo[i].contains("name=")) {
                //设置包名
                int pos = packInfo[i].indexOf("name=") + "name=".length();
                apkInfo.setPackName(packInfo[i].substring(pos));
            } else if (packInfo[i].contains("versionCode=")) {
                //设置版本号
                int pos = packInfo[i].indexOf("versionCode=") + "versionCode=".length();
                String version = packInfo[i].substring(pos);
                apkInfo.setVersion(Integer.parseInt(version));
            } else if (packInfo[i].contains("versionName=")) {
                //设置版本名称
                int pos = packInfo[i].indexOf("versionName=") + "versionName=".length();
                apkInfo.setVersionName(packInfo[i].substring(pos));
            }
        }
    }

    /**
     * 设置应用 标签和图标
     *
     * @param val
     * @param apkInfo
     */
    private static void handleSetAppLabelAndIconsInfo(String val, ApkInfoModel apkInfo) {
        String[] packInfo = val.trim().split(" ");
        int length = packInfo.length;
        for (int i = 0; i < length; i++) {
            if (packInfo[i].contains("label=")) {
                //设置标签
                int pos = packInfo[i].indexOf("label=") + "label=".length();
                apkInfo.setApplicationLabel(packInfo[i].substring(pos));
            } else if (packInfo[i].contains("icon=")) {
                //设置图标
                int pos = packInfo[i].indexOf("icon=") + "icon=".length();
                apkInfo.setIcons(packInfo[i].substring(pos));
            }
        }
    }

    /**
     * 设置 启动活动
     *
     * @param val
     * @param apkInfo
     */
    private static void handleSetLaunchableActivity(String val, ApkInfoModel apkInfo) {
        //获取启动活动
        String[] packInfo = val.trim().split(" ");
        int length = packInfo.length;
        for (int i = 0; i < length; i++) {
            if (packInfo[i].contains("name=")) {
                //设置启动活动
                int pos = packInfo[i].indexOf("name=") + "name=".length();
                apkInfo.setLaunchableActivity(packInfo[i].substring(pos));
            }
        }
    }


    /*************** === 测试结果 === ********************* ===start=== ***************************************/

    public static void main(String[] args) {

    }
}
